# -*- coding: utf-8 -*-

import onlinebrary.lib.converter.feedparser as feedparser
from onlinebrary.model.feed_data import FeedData

import logging
log = logging.getLogger(__name__)


class FeedDiscoverer(object):

        def __init__(self):
            pass
        
        def get_info(self, raw_url):
            
            if raw_url[:7] != 'http://':
                url = 'http://' + raw_url
            else:
                url = raw_url
            
            feed = feedparser.parse(url)
            
            if feed.version == "" or feed['bozo'] == 1:
                if feed.has_key('bozo_exception'):
                    error = feed['bozo_exception']
                else:
                    error = 'unknown error'
                log.error("Cannot connect to the server or unknown feed type at %s, error = %s", url, error)
                return Exception('Ошибка. ', error)
            
            if feed['feed'].has_key('title'):
                feedtitle = feed['feed']['title']
            else :
                feedtitle = '(Поток без названия)'
                
            return FeedData(url, feedtitle)
